<template>
  <view class="app-layout">
    <!-- <app-header></app-header> -->
    <view class="app-main">
      <app-sider pageKey="order"></app-sider>
      <view class="app-content">
        <view class="navbar-con">
          <view class="navbar-bar">
            <view v-for="(tab, index) in tabList" :key="index" class="tab-item" :class="{ active: currentTab == index }"
              @click="handlecurrentTab(index)">
              {{ tab }}
            </view>
          </view>
        </view>
        <view class="tabs-wrapper">
          <!--  <u-tabs :list="currentTabList" @click="tabClick1" :scrollable="true" keyName="name"
            :activeStyle="{ color: '#0F90FD', fontWeight: '500', fontSize: '16px' }">
            <template #content="{ item, keyName, index }">
              <view style="position: relative">
                {{ item[keyName] }}
                <u-badge type="error" max="99" :value="0" :absolute="true" :offset="[-10, -25]"></u-badge>
              </view>
            </template>
          </u-tabs> -->
          <u-tabs :list="tabListAll" @click="tabClick1" :scrollable="true" keyName="name"
            :activeStyle="{ color: '#0F90FD', fontWeight: '500', fontSize: '16px' }" v-if='currentTab==0'>
            <template #content="{ item, keyName, index }">
              <view style="position: relative">
                {{ item[keyName] }}
                <u-badge type="error" max="99" :value="item.num" :absolute="true"
                  :offset="getOffset(item.num)"></u-badge>
              </view>
            </template>
          </u-tabs>
          <u-tabs :list="tabList1" @click="tabClick1" :scrollable="true" keyName="name"
            :activeStyle="{ color: '#0F90FD', fontWeight: '500', fontSize: '16px' }" v-if='currentTab==1'>
            <template #content="{ item, keyName, index }">
              <view style="position: relative">
                {{ item[keyName] }}
                <u-badge type="error" max="99" :value="item.num" :absolute="true"
                  :offset="getOffset(item.num)"></u-badge>
              </view>
            </template>
          </u-tabs>
          <u-tabs :list="tabList2" @click="tabClick1" :scrollable="true" keyName="name"
            :activeStyle="{ color: '#0F90FD', fontWeight: '500', fontSize: '16px' }" v-if='currentTab==2'>
            <template #content="{ item, keyName, index }">
              <view style="position: relative">
                {{ item[keyName] }}
                <u-badge type="error" max="99" :value="item.num" :absolute="true"
                  :offset="getOffset(item.num)"></u-badge>
              </view>
            </template>
          </u-tabs>
          <u-tabs :list="tabList3" @click="tabClick1" :scrollable="true" keyName="name"
            :activeStyle="{ color: '#0F90FD', fontWeight: '500', fontSize: '16px' }" v-if='currentTab==3'>
            <template #content="{ item, keyName, index }">
              <view style="position: relative">
                {{ item[keyName] }}
                <u-badge type="error" max="99" :value="item.num" :absolute="true"
                  :offset="getOffset(item.num)"></u-badge>
              </view>
            </template>
          </u-tabs>
        </view>
        <view class="order-search">
          <uni-datetime-picker v-model="range" type="daterange" @maskClick="maskClick" @change="handleTime" />
          <u-search placeholder="请输入订单编号/会员姓名/手机号" v-model="pageInfo.keyword" clearable bgColor="#fff"
            borderColor="#e5e5e5" :showAction="false" @search="handleSearch" @clear="handleClose"></u-search>

          <u-button type="primary" text="搜索" @click="handleSearch"></u-button>
          <u-button :plain="true" text="重置" @click="handleReset"></u-button>
        </view>
        <view class="order-wrapper" v-if="list.length>0">
          <scroll-view scroll-y="true" ref="scrollView" style="height: 100%; margin-right:10px;width:27%"
            @scrolltolower="onScrollToLower">
            <view class="order-con" :class="{ active: itemOrder === (currentTab === 3 ? item.refundId : item.orderId) }"
              v-for="(item, index) in list" :key="index" @click="handelItem(item)">
              <view class="order-top">
                <view class="order-info">
                  <text class="pickup" v-if="item.sceneCode=='pickup'">自提</text>
                  <text class="takeout" v-if="item.sceneCode=='takeout'">外卖</text>
                  <text class="meals">取餐号：</text>
                  <text class="meals-num">{{item.serialNumber}}</text>
                </view>
                <template v-if="currentTab!=3">
                  <view class="order-status" v-if="item.orderStatus == 1">
                    待制作
                  </view>
                  <view class="order-status" style="color: #ff7a00" v-if="item.orderStatus == 0">
                    待支付
                  </view>
                  <view class="order-status" style="color: #54bcbd" v-if="item.orderStatus == 2">
                    制作中
                  </view>
                  <view class="order-status" style="color: #0f90fd" v-if="item.orderStatus ==3">
                    待取餐
                  </view>
                  <view class="order-status" style="color: #5bbe1e" v-if="item.orderStatus ==6">
                    已完成
                  </view>
                  <view class="order-status" style="color: #999999" v-if="item.orderStatus ==7">
                    已取消
                  </view>
                  <view class="order-status" style="color: #ff7a00" v-if="item.orderStatus ==4">
                    待配送
                  </view>
                  <view class="order-status" style="color: #b886f8" v-if="item.orderStatus ==5">
                    配送中
                  </view>
                </template>
                <template v-if="currentTab==3">
                  <view class="order-status" style="color: #ff7a00" v-if="item.refundStatus == 0">
                    待退款
                  </view>
                  <view class="order-status" style="color: #0f90fd" v-if="item.refundStatus == 1">
                    已退款
                  </view>
                </template>
              </view>
              <view class="order-name" v-if="currentTab!=3">订单编号：{{item.orderId}}</view>
              <view class="order-name" v-if="currentTab==3">退款单号：{{item.refundId}}</view>
              <view class="order-name" v-if="currentTab!=3">下单时间：{{item.createDate}}</view>
              <view class="order-name" v-if="currentTab==3">退款申请时间：{{item.applicationDate}}</view>
              <view class="order-bot">
                <text class="order-price">￥{{currentTab!=3?item.totalAmount:item.applicationRefund}}</text>
                <template v-if="currentTab!=3">
                  <view class="order-btn" v-if="item.orderStatus == 1&&item.canRefund"
                    @click="handleProduction(item.orderId,item.sceneCode)">接单制作</view>
                  <view class="order-btn status1" v-if="item.orderStatus == 2 && item.sceneCode=='pickup'"
                    @click="handletakeMeals(item.orderId,item.sceneCode)">通知取餐</view>
                  <view class="order-btn status1" v-if="item.orderStatus == 2 && item.sceneCode=='takeout'"
                    @click="handletakeMeals(item.orderId,item.sceneCode)">通知送货</view>
                  <view class="order-btn status2" v-if="item.orderStatus == 6" @click="printReceipt">打印小票</view>
                  <view class="order-btn status2" v-if="item.orderStatus ==3" @click="handleFinish(item.orderId)">完成订单
                  </view>
                  <view class="order-btn status2" v-if="item.orderStatus ==5"
                    @click="handledeliveryFinish(item.orderId)">
                    配送完成</view>
                  <view class="order-btn status3" v-if="item.orderStatus ==4" @click="handleShipping(item.orderId)">发货
                  </view>
                </template>
                <template v-else>
                  <view class="order-btn status3" v-if="item.refundStatus == 0" @click.stop="handleRound(item)">退款
                  </view>
                </template>

              </view>
            </view>
            <view style="text-align: center;" v-if="noMoreData&&list.length>0">
              <view class="text1" style="color: #999;">到底了~</view>
            </view>
          </scroll-view>
          <template v-if="detailInfo && Object.keys(detailInfo).length > 0">
            <view style="flex:1;display:flex" v-if="currentTab!=3">
              <view class="order-detail-wrapper">
                <view class="order-detail">
                  <view class="order-tit"> 订单详情 </view>
                  <u-line color="#ECECEC"></u-line>
                </view>
                <scroll-view scroll-y="true" ref="scrollView" style="flex: 1; overflow: auto">
                  <view class="detail-list">
                    <view v-for="(itemD, indexD) in detailList" :key="indexD">
                      <view class="list-item">
                        <view class="list-ite">
                          <image :src="itemD.mainImage"></image>
                          <view class="detail-info">
                            <view class="detail-top">
                              <view class="name">
                                {{ itemD.name }}
                              </view>
                              <view class="parice"> ￥{{itemD.itemPrice}} </view>
                            </view>
                            <view class="detail-bot">
                              <view class="info"> {{itemD.productCombo}}</view>
                              <view class="num"> x{{itemD.productQuantity}} </view>
                            </view>
                          </view>

                        </view>
                        <view class="detail-refound" @click="seeRefunddetails(itemD.orderId)"
                          v-if="itemD.refundNum != null &&itemD.refundNum>=0">
                          <view class="info" v-if="itemD.refundNum>0"> 退款数量：x{{itemD.refundNum}} </view>
                          <view class="num">查看退款详情 ></view>
                        </view>
                      </view>
                      <view class="list-item" v-for="(_ite, _ind) in itemD.children" :key="_ind">
                        <view class="item-menu">
                          {{ itemD.name }}
                        </view>
                        <image src="https://image.yueheji.com/SFA/default/1737811749160.png" mode=""></image>
                        <view class="detail-info">
                          <view class="detail-top">
                            <view class="name">
                              {{ _ite.name }}
                            </view>
                            <view class="parice"> ￥10.00 </view>
                          </view>
                          <view class="detail-bot">
                            <view class="info"> 正常冰，正常糖，西柚粒*1，玫果冻*2 </view>
                            <view class="num"> x1 </view>
                          </view>

                          <view class="detail-refound">
                            <view class="info"> 退款数量：x1 </view>
                            <view class="num"> 查看退款详情 ></view>
                          </view>
                        </view>
                      </view>
                    </view>
                  </view>
                </scroll-view>
                <view class="detail-foot">
                  <view class="foot-info">
                    <text class="sum">共{{detailInfo.totalNum}}件商品，合计</text>
                    <text class="pri">￥{{detailInfo.totalAmount}}</text>
                  </view>
                  <view class="foot-btn">

                    <!-- 制作中 自取 -->
                    <template v-if="detailInfo.orderStatus==2">
                      <view class="order-btn status2" v-if="detailInfo.sceneCode=='pickup'"
                        @click="handletakeMeals(detailInfo.orderId,detailInfo.sceneCode)" style="padding:6px 15px">通知取餐
                      </view>
                      <view class="order-btn status2" v-if="detailInfo.sceneCode=='takeout'"
                        @click="handletakeMeals(detailInfo.orderId,detailInfo.sceneCode)" style="padding:6px 15px">通知送货
                      </view>
                    </template>
                    <!-- 已完成 -->
                    <template v-if="detailInfo.orderStatus==6">
                      <view class="order-btn status5" style="margin-right: 10px;padding:6px 12px"
                        @click="goRefund(detailInfo.orderId)">退款
                      </view>
                      <view class="order-btn status4" style="padding:6px 15px" @click="printReceipt">打印小票</view>
                    </template>
                    <!-- 待制作 -->
                    <template v-if="detailInfo.orderStatus==1">
                      <view class="order-btn status5" style="margin-right: 10px;padding:6px 12px"
                        @click="goRefund(detailInfo.orderId)">退款
                      </view>
                      <view class="order-btn status2" style="padding:6px 15px"
                        @click="handleProduction(detailInfo.orderId,detailInfo.sceneCode)" v-if="detailInfo.canRefund">
                        接单制作</view>
                    </template>


                    <!-- 待取餐 -->
                    <template v-if="detailInfo.orderStatus==3">
                      <view class="order-btn status4" style="padding:6px 15px" @click="printReceipt">打印小票</view>
                      <view class="order-btn status2" style="padding:6px 15px"
                        @click="handleFinish(detailInfo.orderId)">
                        完成订单</view>
                    </template>
                    <!-- 待配送 -->
                    <template v-if="detailInfo.orderStatus==4">
                      <view class="order-btn status2" style="padding:6px 21px"
                        @click="handleShipping(detailInfo.orderId)">去发货</view>
                    </template>
                    <!-- 配送中 -->
                    <template v-if="detailInfo.orderStatus==5">
                      <view class="order-btn status2" style="padding:6px 15px"
                        @click="handledeliveryFinish(detailInfo.orderId)">配送完成</view>
                    </template>
                  </view>
                </view>
              </view>

              <view style="height: 100%; width:38%" :key="infoKey">
                <information :detailInfo="detailInfo" />
              </view>
            </view>

            <view style="height: 100%; display: flex;
            flex-direction: column;
            overflow: hidden;flex:1" v-if="currentTab==3">
              <refundInformation style="display: flex;height: 100%;" :detailInfo="detailInfo"
                @parentRound="handleRound" />
            </view>
          </template>

          <template v-else>
            <view class="order-tip-wrapper">
              <image src="/static/imgs/jiantou.png" mode=""></image>
              <text>请在左侧列表选择所需查看订单~</text>
            </view>
          </template>
        </view>

        <view class="empty-box" style="text-align: center;padding-top: 5vh;" v-else>
          <image src="/src/static/imgs/emptyW.png" mode="widthFix" style="width: 240px;"></image>
          <view class="text1" style="color: #999;">暂无数据</view>
        </view>

      </view>
    </view>
    <view class="floating-button" v-if="list.length>0">
      <image src="../../static/imgs/refresh.png" mode="" @click="handelrefresh"></image>
    </view>
  </view>
  <customPopup v-if="showPopup" :showPopup="showPopup" :typePopup="typePopup" :titPopup="titPopup"
    :infoPopup="infoPopup" :inputType="inputType" @cancelPopup="cancelPopup" @surePopup="surePopup" />
</template>
<script setup>
  import information from './components/information.vue'
  import refundInformation from './components/refundInformation.vue'
  import {
    ref,
    computed,
    reactive
  } from 'vue'
  import {
    onLoad,
    onShow
  } from '@dcloudio/uni-app'
  import {
    getOrderPage,
    getOrder,
    pickupProduction,
    pickupTakeMeals,
    pickupFinish,
    refundSubmit,
    takeOutProduction,
    takeOutDelivery,
    takeOutShipping,
    takeOutFinish,
    getOrderRefund,
    getRefundForSys,
    statistics,
    statisticsRefund
  } from '@/requests/apis/order'
  import customPopup from '@/components/customPopup/index.vue'
  let isMergeRequest = ref(false);
  let infoKey = ref(0)
  let refundOrderId = ref(undefined)
  let range = ref([])
  let refundItem = ref()
  let noMoreData = ref(false);
  let showPopup = ref(false)
  let titPopup = ref('')
  let typePopup = ref()
  let inputType = ref('text')
  let infoPopup = ref('')
  let itemName = ref()
  let itemOrder = ref()
  let currentTab = ref(0)
  let tabList = ref(['全部', '门店自提', '外卖配送', '售后订单'])
  const tabListAll = ref([{
      name: '全部',
      status: undefined,
    },
    {
      name: '待支付',
      status: 0
    },
    {
      name: '待制作',
      status: 1
    },
    {
      name: '制作中',
      status: 2
    },
    {
      name: '待取餐',
      status: 3
    },
    {
      name: '待配送',
      status: 4
    },
    {
      name: '配送中',
      status: 5
    },
    {
      name: '已完成',
      status: 6
    },
    {
      name: '已取消',
      status: 7
    },
  ])
  const tabList1 = ref([{
      name: '全部',
      status: undefined
    },
    {
      name: '待支付',
      status: 0
    },
    {
      name: '待制作',
      status: 1
    },
    {
      name: '制作中',
      status: 2
    },
    {
      name: '待取餐',
      status: 3
    },
    {
      name: '已完成',
      status: 6
    },
    {
      name: '已取消',
      status: 7
    },
  ])
  const tabList2 = ref([{
      name: '全部',
      status: undefined
    },
    {
      name: '待支付',
      status: 0
    },
    {
      name: '待制作',
      status: 1
    },
    {
      name: '制作中',
      status: 2
    },
    {
      name: '待配送',
      status: 4
    },
    {
      name: '配送中',
      status: 5
    },
    {
      name: '已完成',
      status: 6
    },
    {
      name: '已取消',
      status: 7
    },
  ])
  const tabList3 = ref([{
      name: '全部',
      status: undefined
    },
    {
      name: '待退款',
      status: 8
    },
    {
      name: '已退款',
      status: 9
    },
  ])

  const list = ref([])
  let pageInfo = reactive({
    total: 0,
    page: 1,
    limit: 20,
    status: undefined,
    orderStatus: undefined,
    sceneCode: undefined,
    startDate: undefined,
    endDate: undefined,
  });
  let detailInfo = ref()
  let detailList = ref([])
  let storeInfo = ref()
  onLoad(() => {})
  onShow(() => {
    const app = getApp();
    const params = app.globalData.switchTabParams;
    if (params) {
      console.log("拿到参数：", params.type);
      if (params.type=='refund') {
        currentTab.value = 3
        detailInfo.value = {}
        itemOrder.value = undefined
      }else if(params.type=='take') {
        currentTab.value = 0
        detailInfo.value = {}
        itemOrder.value = undefined
      }
      app.globalData.switchTabParams = null;
    }
    // #ifdef APP-PLUS
    uni.hideTabBar()
    // #endif
    // currentTab.value=0
    // pageInfo.value
    // getPageCount()
    getMerge();
    let res = uni.getStorageSync("storeInfo")
    storeInfo.value = res
  });
  const getOffset = (num) => {
    const str = (num || 0).toString();
    const len = str.length;
    // 根据字符长度返回不同的offset值
    if (len === 1) {
      return [-10, -15]; // 1位数字的偏移
    } else if (len === 2) {
      return [-10, -25]; // 2位数字的偏移
    } else {
      return [-10, -30]; // 3位及以上数字的偏移
    }
  };
  const onScrollToLower = () => {
    if (pageInfo.page * pageInfo.limit < pageInfo.total && list.value.length >= 20) {
      pageInfo.page++;
      getData('add');
    } else {
      noMoreData.value = true;
    }
  }
  const getMerge = () => {
    const prevPage = pageInfo.page;
    if (prevPage !== 1) {
      isMergeRequest.value = true;
      pageInfo.limit = prevPage * 20;
      pageInfo.page = 1;
      getData('merge');
    } else {
      pageInfo.page = 1;
      pageInfo.limit = 20;
      getData('refresh');
    }
  };
  const getPageCount = async () => {
    let fun = currentTab.value == 3 ? statisticsRefund : statistics
    let res = await fun()
    let data = res.Result
    if (currentTab.value == 0) {
      tabListAll.value.forEach(item => {
        if (item.status == undefined) {
          item.num = data.total;
        } else {
          item.num = data.statusSummary[item.status] || 0;
        }
      });
    } else if (currentTab.value == 1) {
      tabList1.value.forEach(item => {
        if (item.status == undefined) {
          item.num = data.sceneSummary.pickup;
        } else {
          item.num = data.detailedStats.pickup[item.status] || 0;
        }
      });
    } else if (currentTab.value == 2) {
      tabList2.value.forEach(item => {
        if (item.status == undefined) {
          item.num = data.sceneSummary.takeout;
        } else {
          item.num = data.detailedStats.takeout[item.status] || 0;
        }
      });
    } else if (currentTab.value == 3) {
      tabList3.value[0].num = data.total
      tabList3.value[1].num = data.unRefund
      tabList3.value[2].num = data.refunded
    }

    // console.log(res, '1111111111')
  }
  const getData = async (type) => {
    uni.showLoading({
      title: '加载中',
      mask: true
    });
    try {
      getPageCount()
      let fun = currentTab.value == 3 ? getOrderRefund : getOrderPage
      const res = await fun({
        ...pageInfo,
        orderId: refundOrderId.value
      });
      const processedRecords = (res?.Result.records || []).map(record => {
        const itemNum = record.itemNum || 0;
        const refundNum = record.refundNum || 0;
        return {
          ...record,
          canRefund: itemNum !== refundNum
        };
      });
      pageInfo.total = res?.Result.total || 0;
      if (type === 'merge') {
        list.value = processedRecords;
        pageInfo.page = Math.ceil(list.value.length / 20);
        pageInfo.limit = 20;
        isMergeRequest.value = false;
      } else if (type === 'add') {
        list.value = [...list.value, ...processedRecords];
      } else {
        list.value = processedRecords || [];
      }
    } catch (error) {
      console.log(error);
    } finally {
      uni.hideLoading();
    }
  };
  const currentTabList = computed(() => {
    switch (currentTab.value) {
      case 0:
        return tabListAll.value
      case 1:
        return tabList1.value
      case 2:
        return tabList2.value
      case 3:
        return tabList3.value
      default:
        return []
    }
  })
  const handleTime = (e) => {
    if (e.length > 0) {
      pageInfo.startDate = e[0] + ' ' + '00:00:00'
      pageInfo.endDate = e[1] + ' ' + '23:59:59'
    } else {
      pageInfo.startDate = undefined
      pageInfo.endDate = undefined
    }
  }
  const handleSearch = () => {
    pageInfo.limit = 20;
    pageInfo.page = 1;
    detailInfo.value = {}
    list.value = []
    itemOrder.value = ""
    noMoreData.value = false
    getData()
  }
  const handleReset = () => {
    pageInfo.limit = 20;
    pageInfo.page = 1;
    pageInfo.keyword = ''
    pageInfo.startDate = undefined
    pageInfo.endDate = undefined
    range.value = []
    list.value = []
    detailInfo.value = {}
    itemOrder.value = ""
    refundOrderId.value = ""
    noMoreData.value = false
    getData()
  }
  const handelrefresh = () => {
    getMerge();
    if (itemOrder.value) {
      handelItems()
    }

  }
  const handleClose = () => {
    pageInfo.limit = 20;
    pageInfo.page = 1;
    pageInfo.keyword = ''
    list.value = []
    detailInfo.value = {}
    itemOrder.value = ""
    refundOrderId.value = ""
    noMoreData.value = false
    getData()
  }
  const handlecurrentTab = (index) => {
    currentTab.value = index
    if (index == 1) {
      pageInfo.sceneCode = 'pickup'
    } else if (index == 2) {
      pageInfo.sceneCode = 'takeout'
    } else {
      pageInfo.sceneCode = undefined
    }
    pageInfo.limit = 20;
    pageInfo.page = 1;
    pageInfo.orderStatus = undefined;
    list.value = []
    detailInfo.value = {}
    noMoreData.value = false
    itemOrder.value = ""
    refundOrderId.value = ""
    getPageCount()
    getData()
  }
  const tabClick1 = (e) => {
    console.log(e, '11111111111')
    // 售后订单 0未退款1已退款
    let obj = {
      "全部": undefined,
      '待退款': 0,
      '已退款': 1,
    };
    if (currentTab.value == 3) {
      pageInfo.orderStatus = undefined;
      pageInfo.status = obj[e.name];
    } else {
      pageInfo.orderStatus = e.status
      pageInfo.status = undefined
    }
    noMoreData.value = false
    pageInfo.limit = 20;
    pageInfo.page = 1;
    list.value = []
    detailInfo.value = {}
    itemOrder.value = ""
    getData()
  }
  // 查看退款金额
  const seeRefunddetails = (id) => {
    refundOrderId.value = id
    currentTab.value = 3
    pageInfo.limit = 20;
    pageInfo.page = 1;
    detailInfo.value = {}
    list.value = []
    itemOrder.value = ""
    noMoreData.value = false
    getData()
  }
  const handelItem = async (item) => {
    if (currentTab.value == 3) {
      itemOrder.value = item.refundId
    } else {
      itemOrder.value = item.orderId
    }
    infoKey.value += 1;
    uni.showLoading({
      title: '加载中',
      mask: true
    });
    let res = {}
    if (currentTab.value == 3) {
      res = await getRefundForSys({
        refundId: item.refundId
      })
    } else {
      res = await getOrder({
        orderId: item.orderId
      })
    }
    detailList.value = res.Result?.orderItemList
    detailInfo.value = res.Result
    if (currentTab.value != 3) {

      // 计算当前订单下所有子项的 refundNum 总和（若 refundNum 为 null/undefined，取 0 避免报错）
      const refundNumSum = detailList.value.reduce(
        (sum, item) => sum + (item.refundNum || 0),
        0
      );
      // 比较“子项退款数总和”与“订单总数量”，相等则设置 canRefund 为 false，否则为 true
      detailInfo.value.canRefund = refundNumSum !== detailInfo.value.totalNum;

    }
    uni.hideLoading();
    console.log(detailInfo.value)
  }

  const handelItems = async () => {
    detailInfo.value = {}
    uni.showLoading({
      title: '加载中',
      mask: true
    });
    let res = {}
    if (currentTab.value == 3) {
      res = await getRefundForSys({
        refundId: itemOrder.value
      })
    } else {
      res = await getOrder({
        orderId: itemOrder.value
      })
    }

    if (res) {
      itemOrder.value = currentTab.value == 3 ? res.Result.refundId : res.Result.orderId
      detailList.value = res.Result?.orderItemList
      detailInfo.value = res.Result
      uni.hideLoading();
    }
  }
  // 接单制作
  const handleProduction = async (id, sceneCode) => {
    uni.showLoading({
      title: '加载中',
      mask: true
    });
    let fun = sceneCode == 'pickup' ? pickupProduction : takeOutProduction
    let res = await fun({
      orderId: id
    })
    if (res.ResponseCode == 1) {
      uni.showToast({
        title: res.Result || '',
        icon: 'success',
      })
      setTimeout(() => {
        getMerge();
        handelItems(id)
      }, 800)

      uni.hideLoading();
    }

  }
  // 通知取餐
  const handletakeMeals = async (id, sceneCode) => {
    uni.showLoading({
      title: '加载中',
      mask: true
    });
    let fun = sceneCode == 'pickup' ? pickupTakeMeals : takeOutDelivery
    let res = await fun({
      orderId: id
    })
    if (res.ResponseCode == 1) {
      uni.showToast({
        title: res.Result || '',
        icon: 'success',
      })
      setTimeout(() => {
        getMerge();
        handelItems(id)
      }, 800)
      uni.hideLoading();
    }
  }
  // 去发货
  const handleShipping = async (id) => {
    uni.showLoading({
      title: '加载中',
      mask: true
    });
    let res = await takeOutShipping({
      orderId: id
    })
    if (res.ResponseCode == 1) {
      uni.showToast({
        title: res.Result || '',
        icon: 'success',
      })
      setTimeout(() => {
        getMerge();
        handelItems(id)
      }, 800)
      uni.hideLoading();
    }
  }
  // 配送完成
  const handledeliveryFinish = async (id) => {
    uni.showLoading({
      title: '加载中',
      mask: true
    });
    let res = await takeOutFinish({
      orderId: id
    })
    if (res.ResponseCode == 1) {
      uni.showToast({
        title: res.Result || '',
        icon: 'success',
      })
      setTimeout(() => {
        getMerge();
        handelItems(id)
      }, 800)
      uni.hideLoading();
    }
  }
  // 完成订单
  const handleFinish = async (id) => {
    uni.showLoading({
      title: '加载中',
      mask: true
    });
    let res = await pickupFinish({
      orderId: id
    })
    if (res.ResponseCode == 1) {
      uni.showToast({
        title: res.Result || '',
        icon: 'success',
      })
      setTimeout(() => {
        getMerge();
        handelItems(id)
      }, 800)
      uni.hideLoading();
    }
  }
  // 退款
  const handleRound = (item) => {
    showPopup.value = true
    refundItem.value = item.refundId
    titPopup.value = '请输入退款确认码'
    infoPopup.value = '请输入'
  }
  // 去退款
  const goRefund = (orderId) => {
    uni.navigateTo({
      url: `/pages/order-refund/index?orderId=${orderId}`
    })
  }
  // 打印小票
  const printReceipt = () => {
    uni.showToast({
      title: '等待开发~',
      icon: 'none'
    });
  }
  const cancelPopup = () => {
    showPopup.value = false

  }

  // 弹窗确认
  const surePopup = async (type, value) => {
    uni.showLoading({
      title: '加载中',
      mask: true
    });
    showPopup.value = false;
    try {
      const res = await refundSubmit({
        refundId: refundItem.value,
        code: value,
        deptId: storeInfo.value.deptId
      });

      if (res.ResponseCode == 1) {
        console.log("zouzheli1")
        uni.showToast({
          title: res.Result,
          icon: 'success'
        });
        setTimeout(() => {
          getMerge();
          handelItems()
        }, 800)
      } else {
        uni.showToast({
          title: res.Result || '操作失败',
          icon: 'none'
        });
      }
    } catch (error) {

      console.error('退款提交异常:', error);
    } finally {
      uni.hideLoading();
    }
  };
</script>
<style lang="scss" scoped src="./index.scss"></style>
